package com.antdant.controller;

import com.antdant.common.GeneralResponse;
import com.antdant.config.ConfigInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;

/**
 * @Author Lee Yunc
 * @Date 2021/3/8 9:47
 * @Description: 文件上传接口
 * @Version 1.0
 */
@Slf4j
@RestController
public class FileController extends BaseController {

    @Resource
    private ConfigInfo configInfo;

    @RequestMapping("/file/upload")
    public GeneralResponse upload(@RequestParam("file") MultipartFile file) throws IOException {
        boolean flag = false;
        if (file.isEmpty()) {
            log.info("文件为空");
        } else {
            //如果这里没有设置路径的话，会默认保存在项目的根目录下
            String fileName = file.getOriginalFilename();
            String filePath = configInfo.getPath();
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
                log.info("父目录不存在，已自动创建");
            }
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath + fileName));
            outputStream.write(file.getBytes());
            outputStream.flush();
            outputStream.close();
            flag = true;
        }
        return flag ? success("上传成功") : failed("上传失败");
    }
}
